package com.hy.schedule.util;

import com.hy.schedule.config.TaskSchedulerConfig;
import com.hy.schedule.entity.Task;
import jakarta.annotation.Resource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ScheduledFuture;

/**
 * Created With IntelliJ IDEA.
 * Descriptions:
 * author: Mr.Du
 * Date: 2023/6/9
 * Time: 14:16
 */
@Component
public class ScheduleUtils {
    
    @Resource
    private ThreadPoolTaskScheduler scheduler;
    
    public void startSchedule(){
        
        getTasks().forEach(task -> {
            // 开始执行调度
            ScheduledFuture scheduledFuture = scheduler.schedule(task, new CronTrigger(task.getCron()));
            // 将 scheduledFuture 保存下来用于停止任务使用
            TaskSchedulerConfig.cacheMap.put(task.getId(), scheduledFuture);
        });
    }
    
    
    public void stopSchedule(Long taskId) {
        if (TaskSchedulerConfig.cacheMap.isEmpty()) return;
        if (TaskSchedulerConfig.cacheMap.get(taskId) == null) return;
        
        ScheduledFuture scheduledFuture = TaskSchedulerConfig.cacheMap.get(taskId);
        
        if (scheduledFuture != null) {
            scheduledFuture.cancel(true);   // 这里需要使用指定的 scheduledFuture 来停止当前的线程
            TaskSchedulerConfig.cacheMap.remove(taskId);        // 移除缓存
        }
    }
    
    public void stopAll(){
        if (TaskSchedulerConfig.cacheMap.isEmpty()) return;
        TaskSchedulerConfig.cacheMap.values().forEach(scheduledFuture -> scheduledFuture.cancel(true) );
    }
    
    private List<Task> getTasks(){
        return Arrays.asList(new Task(1L, "任务一", "0/2 * * * * ?"),
                new Task(2L,"任务二", "0/3 * * * * ?"));
    }
    
}
